package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    /**
     * 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> add(@RequestBody Orders orders) {
        ordersService.add(orders);
        return R.success("提交订单成功");
    }

    /**
     * 展示当前用户最新订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userpage(Long page, Long pageSize) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        log.info(BaseContext.getCurrentId().toString());
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo,wrapper);
        //复制订单内容
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");
        //为Dto设置数量和订单详情
        List<OrdersDto> dtos = pageInfo.getRecords().stream().map(item->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            //查询订单详情
            List<OrderDetail> list = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId, item.getId()));
            ordersDto.setOrderDetails(list);
            /*AtomicReference<Integer> num = new AtomicReference<>(0);
            list.stream().map(ele->{
                num.updateAndGet(v -> v + ele.getNumber());
                return ele;
            }).collect(Collectors.toList());
            ordersDto.setSumNum(num.get());*/
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(dtos);
        return R.success(ordersDtoPage);
    }
    @PostMapping("/again")
    public R again(@RequestBody Orders orders) {
        //条件构造器，得到订单详细信息
        LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(qw);
        //向购物车添加数据
        List<ShoppingCart> carts = orderDetails.stream().map(item->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setDishId(item.getDishId());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(carts);
        return R.success(null);
    }

    /**
     * 订单明细数据
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(Long page, Long pageSize, String number,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        /*Page<OrderDetail> pageInfo = new Page<>(page,pageSize);
        orderDetailService.page(pageInfo);
        return R.success(pageInfo);*/

        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number!=null,Orders::getNumber,number);
        wrapper.between(beginTime!=null && endTime!=null,Orders::getOrderTime,beginTime,endTime);
        ordersService.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }


    /**
     * 派送
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> status(@RequestBody Orders orders) {
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(orders.getId()!=null,Orders::getId,orders.getId());
        wrapper.set(Orders::getStatus,orders.getStatus());
        ordersService.update(wrapper);
        return R.success("更新派送状态成功");
    }
}
